import { stringify } from 'querystring';
import { history } from 'umi';
import { accountLogin } from '@/services/login';
import { setAuthority } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';
import { message } from 'antd';
const Model = {
  namespace: 'login',
  state: {
    status: undefined,
    type:''
  },
  effects: {
    *login({ payload }, { call, put }) {
      try {
        const response = yield call(accountLogin, payload);
        if (response.code === '200') {
          const urlParams = new URL(window.location.href);
          const params = getPageQuery();
          message.success(' 登录成功！');
          let { redirect } = params;
          yield put({ type: 'changeLoginStatus', payload: response.data, });
          if (redirect) {
            const redirectUrlParams = new URL(redirect);
            if (redirectUrlParams.origin === urlParams.origin) {
              redirect = redirect.substr(urlParams.origin.length);

              if (redirect.match(/^\/.*#/)) {
                redirect = redirect.substr(redirect.indexOf('#') + 1);
              }
            } else {
              window.location.href = '/';
              return;
            }
          }

          history.replace(redirect || '/');
        }else{
          message.warning(response.msg || '操作异常！')
        }
      } catch (error) {
        message.warning('网络异常！')
      }
    },

    logout() {
      const { redirect } = getPageQuery(); // Note: There may be security issues, please note

      if (window.location.pathname !== '/user/login' && !redirect) {
        sessionStorage.removeItem('user-info')
        history.replace({
          pathname: '/user/login',
          search: stringify({
            redirect: window.location.href,
          }),
        });
      }
    },
  },
  reducers: {
    changeLoginStatus(state, { payload }) {
      setAuthority(payload)
      setUserInfo(payload);
      return {...state, userInfo: payload}
    },
  },
};

export function setUserInfo(authority) {
  sessionStorage.setItem('user-info', JSON.stringify(authority)); // auto reload
}

export function getUserInfo(str) {
  const authorityString =
    typeof str === 'undefined' && sessionStorage ? sessionStorage.getItem('user-info') : str; // authorityString could be admin, "admin", ["admin"]

  let authority;

  try {
    if (authorityString) {
      authority = JSON.parse(authorityString);
    }
  } catch (e) {
    authority = authorityString;
  }

  return authority;
}

export default Model;
